package com.douqu.game.auth.service;


import com.alibaba.fastjson.JSONObject;
import com.bean.core.util.FormatUtils;
import com.bean.core.util.Utils;
import com.douqu.game.auth.database.mapper.AreaMapper;
import com.douqu.game.auth.database.mapper.RoleRecordMapper;
import com.douqu.game.auth.database.mapper.ServerMapper;
import com.douqu.game.auth.database.mapper.WhiteMapper;
import com.douqu.game.auth.database.model.*;
import com.douqu.game.auth.server.SmsCodeCache;
import com.douqu.game.auth.utils.SmsMessageUtil;
import com.douqu.game.auth.web.request.AuthReqDto;
import com.douqu.game.auth.web.request.LoginReqDto;
import com.douqu.game.auth.web.request.RegisterReqDto;
import com.douqu.game.auth.web.request.UpdateRecordReqDto;
import com.douqu.game.auth.web.response.AreaIncludeServerDto;
import com.douqu.game.auth.web.response.PlayerResDto;
import com.douqu.game.auth.web.response.ServerResDto;
import com.douqu.game.auth.web.response.ServesInfoResDto;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.ReturnMessage;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.factory.PlatformFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.web.response.BaseResponseDto;
import com.douqu.game.core.web.response.ErrorResponseDto;
import com.douqu.game.core.web.response.SuccessResponseDto;
import com.douqu.game.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author : wangzhenfei
 * 2017-07-06 15:55
 */
@Service
public class PlayerServiceImpl implements PlayerService {

    @Autowired
    ServerMapper serverMapper;

    @Autowired
    AreaMapper areaMapper;

    @Autowired
    RoleRecordMapper roleRecordMapper;

    @Autowired
    WhiteMapper whiteMapper;

    @Autowired
    ClickActivationService clickActivationService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResponseDto auth(AuthReqDto reqDto) {

        LogUtils.info("auth req:" + reqDto.toString());
        
        String account = reqDto.getAccount();
        String password = reqDto.getPassword();
        String deviceId = reqDto.getDeviceId();
        Integer serverRuleId = reqDto.getServerRuleId();

        Integer gameName;
        Integer serverType;
        Integer platform;
        //旧版本兼容
        if (serverRuleId < 1000){
            int[] result = CoreUtils.oldFormRuleId(serverRuleId);
            gameName = result[0];
            serverType = result[1];
            platform = result[2];
        }else{
            int[] result = CoreUtils.formRuleId(serverRuleId);
            gameName = result[0];
            serverType = result[1];
            platform = result[2];
        }

        //官方百度会进行激活验证
        if (serverType == SGCommonProto.E_SERVER_TYPE.SERVER_TYPE_OFFICIAL_VALUE
                && platform == SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_BAI_DU_VALUE)
            clickActivationService.testActivation(platform, reqDto.getImei());

        LogUtils.info("auth gameName:" + gameName + " serverType:" + serverType + " platform:" + platform);
        if (gameName == SGCommonProto.E_GAME_NAME.GAME_NAME_UNKNOW_VALUE)
            return new BaseResponseDto(ReturnMessage.GAMENAME_ERROR);

        if (serverType == SGCommonProto.E_SERVER_TYPE.SERVER_TYPE_UNKNOW_VALUE)
            return new BaseResponseDto(ReturnMessage.SERVERTYPE_ERROR);

        if (platform == SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_UNKNOW_VALUE)
            return new BaseResponseDto(ReturnMessage.PLATFORM_ERROR);
        //验证用户账号 以及 deviceId 不能为空
        if(StringUtils.isNullOrEmpty(account) && StringUtils.isNullOrEmpty(deviceId)){
            return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
        }
        //登录渠道不能为空
        if(SGCommonProto.E_CHANNEL_TYPE.forNumber(reqDto.getChannel()) == null){
            return new ErrorResponseDto(ReturnMessage.NO_CHANNEL);
        }

//        Class  cls = PhoneImpl.class;
//        switch (reqDto.getChannel()){
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK_VALUE:
//                if(StringUtils.isNullOrEmpty(deviceId)){
//                    return new ErrorResponseDto(ReturnMessage.DEVICE_ID_NOT_NULL);
//                }
//                cls = DeviceIdImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = PhoneImpl.class;
//                break;
//
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QQ_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = QQImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_WECHAT_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = WechatImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_YJ_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = YJImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QIANGWAN_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = QWImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_JITUO_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = JTImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PINGPING_VALUE:
//                if(StringUtils.isNullOrEmpty(account))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.ACCOUNT_ILLEGAL);
//                }
//                cls = PPImpl.class;
//                break;
//
//        }
//
//        TwoTuple<RoleRecordModel, ReturnMessage> twoTuple = SpringContext.getPlatformSDK(cls).auth(0, account,  password,  deviceId);
//
//        if(twoTuple.getSecond() != null){ // 有错误
//            return new ErrorResponseDto(twoTuple.getSecond());
//        }
//
//        RoleRecordModel recordModel = twoTuple.getFirst();

        SGCommonProto.E_CHANNEL_TYPE channelType = SGCommonProto.E_CHANNEL_TYPE.forNumber(reqDto.getChannel());
        if(channelType == null)
        {
            LogUtils.error("认证渠道不存在 -> " + reqDto.getChannel());
            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
        }

        String newAccount = PlatformFactory.auth(channelType, channelType== SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK?reqDto.getDeviceId():reqDto.getAccount(), reqDto.getPassword());
        if(Utils.isNullOrEmpty(newAccount))
        {
            LogUtils.error("认证失败 -> channelType:" + channelType + ", data:" + JSONObject.toJSONString(reqDto));
            return new ErrorResponseDto(ReturnMessage.AUTH_FAILURE);
        }

        RoleRecordModel recordModel = getUserRecordByAccount(newAccount);
        if (recordModel == null) {//需要创建
            recordModel = new RoleRecordModel();
            recordModel.setAccount(newAccount);
            recordModel.setChannel(reqDto.getChannel());
            recordModel.setServerId(0);
            LogUtils.info("第一次登录，创建用户");
        }

        AreaIncludeServerDto resDto = new AreaIncludeServerDto();
        List<ServerResDto> servers = new ArrayList<>();

        /**
         * 1.根据gameName serverType platform 获取服务器规则id
         * 2.根据规则得到最新的一个服务器
         */
        ServerModel newServerModel = serverMapper.getNewServer(serverRuleId);
        int newServerId = newServerModel == null ? 0 : newServerModel.getId();

        ServerModel serverModel = null;
        Integer serverId = 0;
        if(recordModel != null){
            //获取最近登录的服务器
            //这里也要验证是否是符合规则的服务器 不然为null
            serverId = roleRecordMapper.gerRecentLoginServerId(reqDto.getChannel() != SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK_VALUE?
                    recordModel.getAccount() : recordModel.getDeviceId());
        }
        serverId = serverId == null? 0: serverId.intValue();

        if(serverId != 0){
            serverModel = serverMapper.selectByKeyAndRule(serverId, serverRuleId);
        }
        AreaModel areaModel = null;
        if(serverModel != null){
            servers.add(new ServerResDto(serverModel, newServerId));
            areaModel = areaMapper.selectByPrimaryKey(serverModel.getAreaId());
        }else{
            if(newServerModel != null){
                servers.add(new ServerResDto(newServerModel, newServerId));
                areaModel = areaMapper.selectByPrimaryKey(newServerModel.getAreaId());
            }
        }
        if (areaModel != null){
            resDto.setAreaId(areaModel.getId());
            resDto.setAreaName(areaModel.getName());
        }

        resDto.setServers(servers);
//        resDto.getServers().get(0).setPort(11111);

        //如果获取规则组的id获取公告 如果写多了只显示一个

        NoticeMessageModel postMessageModel = serverMapper.getNotice(platform);
        if(postMessageModel != null && postMessageModel.getShow() == 1){
            resDto.setNotice(postMessageModel.getContent());
            resDto.setAutoShowNotice(postMessageModel.isAutoShowNotice());
        }

        resDto.setAccount(account);
        resDto.setPassword(password);
        resDto.setChannel(reqDto.getChannel());

        //快速登录是否是绑定手机的
        if(reqDto.getChannel() == SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK_VALUE){
            List<RoleRecordModel> models = getUserRecordByDevice(recordModel.getDeviceId());
            if(models != null && models.size() > 0){
                if(!StringUtils.isNullOrEmpty(models.get(0).getAccount())){
                    resDto.setHasBandPhone(1);
                }
            }else{//未注册
                resDto.setHasBandPhone(1);
            }

        }else {
            resDto.setHasBandPhone(1);
        }
        LogUtils.info("auth 返回:\n" + resDto);
        return new SuccessResponseDto(resDto);
    }

    @Override
    public List<RoleRecordModel> getUserRecordByDevice(String deviceId)
    {
        return roleRecordMapper.getByDeviceId(deviceId);
    }

    @Override
    public RoleRecordModel getUserRecordByAccount(String device)
    {
        return roleRecordMapper.getByAccount(device);
    }


    @Override
    public BaseResponseDto register(RegisterReqDto register) {

        LogUtils.info("register:" + register.toString());

        if(register == null){
            return new ErrorResponseDto(ReturnMessage.EMPTY_PARAM);
        }

//        Class  cls = PhoneImpl.class;
//        switch (register.getChannel()){
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getDeviceId())){
//                    return new ErrorResponseDto(ReturnMessage.DEVICE_ID_NOT_NULL);
//                }
//                cls = DeviceIdImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = PhoneImpl.class;
//
//                break;
//
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QQ_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = QQImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_WECHAT_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = WechatImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_YJ_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = YJImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QIANGWAN_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = QWImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_JITUO_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = JTImpl.class;
//                break;
//            case SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PINGPING_VALUE:
//                if(StringUtils.isNullOrEmpty(register.getAccount()))
//                {
//                    LogUtils.debug("账号为空!");
//                    return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
//                }
//                cls = PPImpl.class;
//                break;
//
//        }

        //兼容旧版本
        TdInfoDetail tdInfoDetail = new TdInfoDetail();
        //验证talkingData要的数据
        if (register.getServerRuleId() != 0){
//            LogUtils.debug("游戏名服务器类型渠道id 三合一码为空!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
        }
        if (!StringUtils.isNullOrEmpty(register.getClientVersion())){
//            LogUtils.debug("客户端版本号为空!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            tdInfoDetail.setClientVersion(register.getClientVersion());
        }
        if (!StringUtils.isNullOrEmpty(register.getOsversion())){
//            LogUtils.debug("OS版本为空!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            tdInfoDetail.setOsversion(register.getOsversion());
        }
        if (!StringUtils.isNullOrEmpty(register.getTdid())){
//            LogUtils.debug("talkingData设备id为空!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            tdInfoDetail.setTdDeviceId(register.getTdDeviceId());
        }
        if (!StringUtils.isNullOrEmpty(register.getTdDeviceId())){
//            LogUtils.debug("taldingData的deviceID为空!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            tdInfoDetail.setTdDeviceIdType(register.getTdDeviceIdType());
        }
        SGCommonProto.E_TD_DEVICEID_TYPE deviceid_type = SGCommonProto.E_TD_DEVICEID_TYPE.forNumber(register.getTdDeviceIdType());
        if (deviceid_type != null && deviceid_type != SGCommonProto.E_TD_DEVICEID_TYPE.TD_DEVICEID_UNKNOWN){
//            LogUtils.debug("talkingData的deviceIdType错误!");
//            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
            tdInfoDetail.setTdid(register.getTdid());
        }

        Integer serverId = register.getServerId() == null? 0 : register.getServerId().intValue();
        SGCommonProto.E_CHANNEL_TYPE channelType = SGCommonProto.E_CHANNEL_TYPE.forNumber(register.getChannel());
        if(channelType == null)
        {
            LogUtils.error("注册 认证渠道不存在 -> " + register.getChannel());
            return new ErrorResponseDto(ReturnMessage.PARAM_ERROR);
        }

        String newAccount = PlatformFactory.auth(channelType, channelType== SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK?register.getDeviceId():register.getAccount(), register.getPassword());
        if(Utils.isNullOrEmpty(newAccount))
        {
            LogUtils.error("注册 认证失败 -> channelType:" + channelType + ", data:" + JSONObject.toJSONString(register));
            return new ErrorResponseDto(ReturnMessage.AUTH_FAILURE);
        }

//        TwoTuple<RoleRecordModel, ReturnMessage> twoTuple = SpringContext.getPlatformSDK(cls).auth(serverId, register.getAccount(),
//                register.getPassword(),  register.getDeviceId());
//
//        if(twoTuple.getSecond() != null){ // 有错误
//            return new ErrorResponseDto(twoTuple.getSecond());
//        }

        //检查服务器是否存在
        ServerModel serverModel = serverMapper.selectByPrimaryKey(serverId);
        if(serverModel == null){
            return new ErrorResponseDto(ReturnMessage.SERVER_ID_ERROR);
        }

        //检查同名
        RoleRecordModel recordModel = roleRecordMapper.getByPlayName(register.getPlayName());
        if(recordModel != null){
            return new ErrorResponseDto(ReturnMessage.NICKNAME_EXITS);
        }

        String key = register.getChannel() != SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK_VALUE ?
                register.getAccount() : register.getDeviceId();
        //检查是否同一个服务器创建多个角色
        List<RoleRecordModel> recordModels = roleRecordMapper.gerRecordsByAccountOrDeviceId(CoreUtils.createAccount(key,
                SGCommonProto.E_CHANNEL_TYPE.forNumber(register.getChannel())));
        boolean hasRegister = false;
        for(RoleRecordModel model : recordModels){
            if(model.getServerId() == serverId){
                hasRegister = true;
                break;
//                return new ErrorResponseDto(ReturnMessage.THIS_SERVER_PLAYER_EXITS);
            }
        }
        if(!register.isJustCheck()){
            if(hasRegister){ //曾经注册过，直接更改信息
                roleRecordMapper.update(CoreUtils.createAccount(key,
                                SGCommonProto.E_CHANNEL_TYPE.forNumber(register.getChannel())),
                        serverId,
                        register.getAvatar(),
                        register.getPlayName(),register.getLevel(),register.getServerRuleId(),JSONObject.toJSONString(tdInfoDetail));
            }else {
                recordModel = getUserRecordByAccount(newAccount);
                if(recordModel == null)
                {
                    recordModel = new RoleRecordModel();
                    recordModel.setAccount(newAccount);
                    recordModel.setChannel(register.getChannel());
                }
                recordModel.setPlayerName(register.getPlayName());
                recordModel.setIp(register.getIp());
                recordModel.setAvatar(register.getAvatar());
                recordModel.setLevel(register.getLevel());
                recordModel.setServerId(register.getServerId());
                recordModel.setObjectIndex(register.getObjectIndex());
                recordModel.setServerRuleId(register.getServerRuleId());
                recordModel.setTdInfo(JSONObject.toJSONString(tdInfoDetail));
                roleRecordMapper.insert(recordModel);
            }

        }
        return new SuccessResponseDto();
    }

    @Override
    public BaseResponseDto loginSuccess(LoginReqDto loginReqDto,HttpServletRequest request, HttpServletResponse response) {
        LogUtils.info("loginSuccess:" + loginReqDto.toString());
        roleRecordMapper.updateLoginTime(loginReqDto.getAccount(), loginReqDto.getServerId(), loginReqDto.getObjectIndex());
        return new SuccessResponseDto();
    }

    @Override
    public BaseResponseDto getServerList(String account,Integer channel, Integer serverRuleId) {
        LogUtils.info("请求服务器列表请求参数 account:" + account + " channel:" + channel + " serverRuleId:" + serverRuleId);
        Integer gameName;
        Integer serverType;
        Integer platform;
        //旧版本兼容
        if (serverRuleId < 1000){
            int[] result = CoreUtils.oldFormRuleId(serverRuleId);
            gameName = result[0];
            serverType = result[1];
            platform = result[2];
        }else{
            int[] result = CoreUtils.formRuleId(serverRuleId);
            gameName = result[0];
            serverType = result[1];
            platform = result[2];
        }

        LogUtils.info("getServerList gameName:" + gameName + " serverType:" + serverType + " platform:" + platform);
        if (gameName == SGCommonProto.E_GAME_NAME.GAME_NAME_UNKNOW_VALUE){
            return new BaseResponseDto(ReturnMessage.GAMENAME_ERROR);
        }
        if (serverType == SGCommonProto.E_SERVER_TYPE.SERVER_TYPE_UNKNOW_VALUE){
            return new BaseResponseDto(ReturnMessage.SERVERTYPE_ERROR);
        }
        if (platform == SGCommonProto.E_PLATFORM_TYPE.PLATFORM_TYPE_UNKNOW_VALUE){
            return new BaseResponseDto(ReturnMessage.PLATFORM_ERROR);
        }
        //最新的服务器
        ServerModel newServerModel = serverMapper.getNewServer(serverRuleId);
        int newServerId = newServerModel == null ? 0 : newServerModel.getId();
        //获取区信息
        List<AreaModel> areas = areaMapper.getList();
        List<ServerModel> servers;
        //如果是白名单

        ServesInfoResDto resDto = new ServesInfoResDto();

        account = CoreUtils.createAccount(account,SGCommonProto.E_CHANNEL_TYPE.forNumber(channel));
        if(whiteMapper.selectCount(account) > 0){
            servers = serverMapper.getListWhite(serverRuleId);
            resDto.setShowConfigVersion(true);
        }else{
            servers = serverMapper.getList(serverRuleId);
            resDto.setShowConfigVersion(false);
        }

        Map<Integer, List<ServerResDto>> map = new HashMap<>();
        List<ServerResDto> recommendList = new ArrayList<>();
        for(ServerModel model : servers){
            List<ServerResDto> list = map.get(model.getAreaId());
            if(list == null){
                list = new ArrayList<>();
                map.put(model.getAreaId(), list);
            }
            list.add(new ServerResDto(model, newServerId));

            if(model.isRecommend())
                recommendList.add(new ServerResDto(model, newServerId));
        }

        resDto.setRecommendServers(recommendList);

        List<AreaIncludeServerDto> aSs = new ArrayList<>();
        for(AreaModel model : areas){
            AreaIncludeServerDto areaServers = new AreaIncludeServerDto();
            areaServers.setAreaId(model.getId());
            areaServers.setAreaName(model.getName());
            areaServers.setNotice("999999999999999999999999");
            aSs.add(areaServers);
            List<ServerResDto> list = map.get(model.getId());
//            if(list != null && !CoreUtils.isRechargeTestAccount(account)){
//                list.remove(new ServerResDto(1));
//            }
            areaServers.setServers(list == null? new ArrayList<ServerResDto>() : list);
        }
        resDto.setAreaServers(aSs);

        //获取推荐列表
//        List<ServerModel> recommendList = serverMapper.getRecommendList(serverRuleId);
//
//        List<ServerResDto> list = new ArrayList<>();
//        if(recommendList != null){
//            for(ServerModel model : recommendList){
//                list.add(new ServerResDto(model, newServerId));
//            }
//        }
//        resDto.setRecommendServers(list);

        //获取我所有的区角色
        List<RoleRecordModel> recordModels = roleRecordMapper.gerRecordsByAccountOrDeviceId(account);
        List<PlayerResDto> plays = new ArrayList<>();
        if(recordModels != null){
            for(RoleRecordModel model : recordModels){
                PlayerResDto player = new PlayerResDto();
                player.setLevel(model.getLevel());
                player.setAvatar(model.getAvatar());
                player.setNickName(model.getPlayerName());
                ServerModel sm = null;
                if (servers != null && !servers.isEmpty()){
                    int index = servers.indexOf(new ServerModel(model.getServerId()));
                    if (index >= 0)
                        sm = servers.get(index);
                }
                if(sm != null) {
                    player.setServer(new ServerResDto(sm, newServerId));
                    plays.add(player);
                }
            }
        }
        resDto.setPlayers(plays);


        LogUtils.info("请求服务器列表返回角色记录:" + plays);

        return new SuccessResponseDto(resDto);
    }


    @Override
    public BaseResponseDto updateRecord(UpdateRecordReqDto reqDto) {
        String key = reqDto.getAccount();
        List<RoleRecordModel> recordModels = roleRecordMapper.gerRecordInServer(reqDto.getAccount(), reqDto.getServerId());
        if(recordModels == null || recordModels.size() == 0){
            return new ErrorResponseDto(ReturnMessage.NO_RECORD);
        }

        if(!StringUtils.isNullOrEmpty(reqDto.getPlayerName())){
            //检查同名
            RoleRecordModel samModel = roleRecordMapper.getByPlayName(reqDto.getPlayerName());
            if(samModel != null){
                return new ErrorResponseDto(ReturnMessage.NICKNAME_EXITS);
            }
        }
        roleRecordMapper.update(key,reqDto.getServerId(), reqDto.getAvatar(), reqDto.getPlayerName(), reqDto.getLevel(),null,null);
        return new SuccessResponseDto();
    }

    @Override
    public BaseResponseDto mergeServer(UpdateRecordReqDto reqDto) {
        String key = reqDto.getAccount();
        List<RoleRecordModel> recordModels = roleRecordMapper.gerRecordInServer(key, reqDto.getServerId());
        if(recordModels == null || recordModels.size() == 0){
            return new ErrorResponseDto(ReturnMessage.NO_RECORD);
        }
        /**
         * 1.首先将所有符合条件的role_record 全部修改为和游戏服传递过来的一致
         * 2.保留一条在list中remove 剩下的全部从数据库删除
         */
        roleRecordMapper.update(key,reqDto.getServerId(), reqDto.getAvatar(), reqDto.getPlayerName(), reqDto.getLevel(),null,null);
        recordModels.remove(0);
        for(RoleRecordModel model : recordModels){
            roleRecordMapper.delete(model.getId());
        }
        return new SuccessResponseDto();
    }

    @Override
    public BaseResponseDto getCaptcha(String phone) {
        if(!FormatUtils.checkPhoneFormat(phone))
        {
            LogUtils.debug("手机号码格式错误:" + phone);
            return new ErrorResponseDto(ReturnMessage.PHONE_NUM_ILLEGAL);
        }
        String result = SmsMessageUtil.sendCaptcha(phone);
        SmsCodeCache.getInstance().addCache(phone, result);
        return new SuccessResponseDto(result);
    }

    /**
     * 充值
     * @param playerController
     */
    @Override
    public boolean recharge( PlayerController playerController, Player player, int rechargeId, int realRmb, String orderNo) {
        return true;

    }

//    @Override
//    public BaseResponseDto bandPhoneNumGetCaptcha(String deviceId, String phoneNum) {
//        if(!FormatUtils.checkPhoneFormat(phoneNum))
//        {
//            LogUtils.debug("手机号码格式错误:" + phoneNum);
//            return new ErrorResponseDto(ReturnMessage.PHONE_NUM_ILLEGAL);
//        }
//
//        String account = Utils.createAccount(phoneNum, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE);
//        if(getUserRecordByAccount(account) != null){
//            LogUtils.debug("该手机号已经注册");
//            return new ErrorResponseDto(ReturnMessage.PHONE_HAS_ALREADY_REGISTER);
//        }
//
//         account = Utils.createAccount(deviceId, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK);
//        List<RoleRecordModel> models = getUserRecordByDevice(account);
//        if(models != null && models.size() > 0){
//            if(!StringUtils.isNullOrEmpty(models.get(0).getAccount())){
//                LogUtils.debug("该设备已经绑定手机号");
//                return new ErrorResponseDto(ReturnMessage.DEVICE_HAS_BAND_PHONE);
//            }
//        }
//
//        String result = SmsMessageUtil.sendCaptcha(phoneNum);
//        return new SuccessResponseDto(result);
//    }

    @Override
    public BaseResponseDto bandPhoneNum(String deviceId, String phoneNum, String captcha) {
        if(!FormatUtils.checkPhoneFormat(phoneNum))
        {
            LogUtils.debug("手机号码格式错误:" + phoneNum);
            return new ErrorResponseDto(ReturnMessage.PHONE_NUM_ILLEGAL);
        }

//        if(!SmsCodeCache.getInstance().checkCode(phoneNum, captcha)){
//            LogUtils.debug("手机号码验证码错误:" + phoneNum);
//            return new ErrorResponseDto(ReturnMessage.SMS_CODE_ERROR);
//        }

        String account = CoreUtils.createAccount(phoneNum, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE);
        if(getUserRecordByAccount(account) != null){
            LogUtils.debug("该手机号已经注册");
            return new ErrorResponseDto(ReturnMessage.PHONE_HAS_ALREADY_REGISTER);
        }

        account = CoreUtils.createAccount(deviceId, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK);
        List<RoleRecordModel> models = getUserRecordByDevice(account);
        if(models != null && models.size() > 0){
            if(!StringUtils.isNullOrEmpty(models.get(0).getAccount())){
                LogUtils.debug("该设备已经绑定手机号");
                return new ErrorResponseDto(ReturnMessage.DEVICE_HAS_BAND_PHONE);
            }
        }else{
            LogUtils.debug("设备不存在");
            return new ErrorResponseDto(ReturnMessage.DEVICE_UN_EXIST);
        }

        roleRecordMapper.updateBandPhone(CoreUtils.createAccount(phoneNum, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE),
                CoreUtils.createAccount(deviceId, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_QUICK));

        return new SuccessResponseDto();
    }

    @Override
    public BaseResponseDto getPhoneBandDevice(String phone) {
        RoleRecordModel model = getUserRecordByAccount(CoreUtils.createAccount(phone, SGCommonProto.E_CHANNEL_TYPE.CHANNEL_TYPE_PHONE));
        return new SuccessResponseDto(model == null ? "" : model.getDeviceId());
    }

    @Override
    public BaseResponseDto getWhiteList() {
        List<String> whiteModelList = whiteMapper.getAll();
        return new SuccessResponseDto(whiteModelList);
    }

}
